package com.example.sachon;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SA1200 extends Activity {

	private List<DetailContentItem> list;
	private DetailContentListAdapter listAdapter;
	private ListView listview;
	private ProgressDialog progressbar;

	private boolean isSubInit = true;
	private EditText selection = null;
	private InputMethodManager imm = null;
	private TextView title = null;

	private String idx;
	private String chon_name;
	private String phone_number;
	private String subPhone_number;
	private String subContent;
	private final String LOGTAG = "SA1200_";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sa1200);

		// 안드로이드 허니컴부터는 메인에서 Thread 사용을 못하는데 아래의 문장을 추가해주면 사요 가능.
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		//글번호 넘겨받기
		try{
			
			ImageView sa1200_title_img_go_home = (ImageView) findViewById(R.id.sa1200_title_img_go_home);
			
			// 홈으로 가기
			sa1200_title_img_go_home.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					try
					{						
						Intent intent = new Intent();
						setResult(RESULT_OK, intent);
						finish();
						
					}
					catch(Exception e) {
						Log.d(LOGTAG,"Exception:" + e.getMessage());
					}
				}
			});
			
			
			Intent intent = getIntent();
			idx = intent.getExtras().getString("idx");
			Log.d(LOGTAG," 글번호:" + idx);
			
			chon_name = Const.getInstance().chonInfo().getChon_nm();
			/*
			 * subPhone_number : 현재 로그인 한 사용자 phone_number
			 */
			subPhone_number = Const.getInstance().userInfo().getPhone_number();
			
			/*
			 * phone_number : 게시글 작성자 
			 */
			phone_number = intent.getExtras().getString("phone_number");
			
			Log.d(LOGTAG," 작성자:" + phone_number+"  로그인 사용자"+subPhone_number);
			
		}catch(Exception e){
			System.out.println("Activity ERROR:" + e.toString());
			e.printStackTrace();
			idx = "5";
			
			chon_name = "TEST";
			phone_number = "01026059153";
		}
		
		readServer();

		// AlertDialog를 활용한 다중 선택 메뉴 생성
		final String[] items = {"게시자에게 전화걸기", "게시자에게 문자보내기", "글 삭제"};
		
		if(phone_number.equals(subPhone_number)){

		}
		
		
		final AlertDialog.Builder builder;
		builder = new AlertDialog.Builder(this);
		builder.setTitle("선택해주세요");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				//Toast.makeText(SA1200.this, items[which] + " 선택!",Toast.LENGTH_SHORT).show();

				switch (which) {
				case 0:
					call();
					break;
				case 1:
					sms();
					break;
				case 2:
					if(phone_number.equals(subPhone_number)){
						delete();//modify();
						
					}else{
						
						Toast.makeText(SA1200.this, "작성자만 삭제 할 수 있습니다.",
								Toast.LENGTH_SHORT).show();
					}
										
					break;
				case 3:
					delete();
					break;
				}
			}
		});
		builder.create();

		findViewById(R.id.menuBtn).setOnClickListener(
				new View.OnClickListener() {

					public void onClick(View v) {
						// TODO Auto-generated method stub
						builder.show();
					}
				});

		findViewById(R.id.subWriteBtn).setOnClickListener(
				new View.OnClickListener() {

					public void onClick(View v) {
						// TODO Auto-generated method stub
						subContent = ((EditText) findViewById(R.id.subContent))
								.getText().toString();

						writeSubContent();
					}
				});

		selection = (EditText) findViewById(R.id.subContent);
		selection.setOnTouchListener(new View.OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				if (event.getAction() == MotionEvent.ACTION_UP) {
					// if (selection.getClass() == v.getClass()) {
					if (isSubInit) {
						isSubInit = false;
						selection.setText("");
					}
					// }
				}

				return false;// stop
			}
		});

		title = (TextView) findViewById(R.id.title);
		//title.setText(chon_name + " - 소 식 지" + " - " + phone_number);
		title.setText(chon_name + " 소식지 - 글 내용");

		imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

	}

	private void call() {
		try {

			Intent callIntent = new Intent(Intent.ACTION_VIEW);

			//callIntent.setData(Uri.parse("tel:01026059153"));
			callIntent.setData(Uri.parse("tel:"+phone_number));

			startActivity(callIntent);

		} catch (ActivityNotFoundException e) {

			Log.e("전화걸기", "전화걸기에 실패했습니다", e);

		}
	}

	private void sms() {
		try {
			Intent smsIntent = new Intent(Intent.ACTION_SENDTO,
					Uri.parse("smsto:target_no1;target_no2"));

			//Uri uri = Uri.parse("sms:" + "01026059153");
			Uri uri = Uri.parse("sms:" + phone_number);
			Intent intent = new Intent(Intent.ACTION_SENDTO, uri);

			// intent.setData(uri);
			// intent.putExtra("address", uri);
			intent.putExtra("sms_body", "게시자에게 문자를 보냅니다.");
			// intent.setType("vnd.android-dir/mms-sms");
			startActivity(intent);
		} catch (ActivityNotFoundException e) {

			Log.e("SMS", "문자보내기에 실패했습니다", e);

		}
	}

	private void modify() {
		//Intent intent = new Intent();
		//intent.setClass(SA1200.this, ViewActivity.class);
		//intent.putExtra("no", "1");

		//startActivityForResult(intent, 100);
	}

	private void delete() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					String postURL = "http://auralizer.cafe24.com/sachon/sa_board_delete.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();

					params.add(new BasicNameValuePair("idx", idx));
					params.add(new BasicNameValuePair("phone_number",
							phone_number));
					
					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient()
							.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity,
								"UTF-8");

						System.out.println("WriteActivity : "
								+ responseString.trim());

						System.out.println("*************************" + responseString.trim());
						if (responseString.trim().equals("SUCCESS")) {
							mHandler.sendEmptyMessage(200);
						} else {
							mHandler.sendEmptyMessage(-200);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		// progressbar = ProgressDialog.show(this, null, "    Loading........");
	}

	private void writeSubContent() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					String postURL = "http://auralizer.cafe24.com/sachon/reply_ok.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();

					params.add(new BasicNameValuePair("idx", idx));
					params.add(new BasicNameValuePair("phone_number",
							subPhone_number));
					params.add(new BasicNameValuePair("subcontent", subContent));

					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient()
							.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity,
								"UTF-8");

						System.out.println("WriteActivity : "
								+ responseString.trim());

						System.out.println("*************************" + responseString.trim());
						if (responseString.trim().equals("SUCCESS")) {
							mHandler.sendEmptyMessage(200);
						} else {
							mHandler.sendEmptyMessage(-100);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		// progressbar = ProgressDialog.show(this, null, "    Loading........");
	}

	private void readServer() {
		Thread thread = new Thread(new Runnable() {
			public void run() {

				try {
					String postURL = "http://auralizer.cafe24.com/sachon/sa_board_view.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();

					// 행번 전달
					params.add(new BasicNameValuePair("idx", idx));

					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient()
							.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity,
								"UTF-8");

						Log.d(LOGTAG," 댓글  : " + responseString.trim());

						if (responseString.trim().equals("FAIL")) {
							mHandler.sendEmptyMessage(0);
						} else {
							list = new ArrayList<DetailContentItem>();

							DetailContentItem listItem2 = null;
							JSONArray jsonArray = new JSONArray(responseString
									.trim());
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray
										.getJSONObject(i);
								DetailContentItem listItem = new DetailContentItem();

								listItem.setMode(0);
								listItem.setIdx(jsonObject.getString("idx"));
								listItem.setPhone_number(jsonObject
										.getString("phone_number"));
								listItem.setUser_name(jsonObject
										.getString("user_name"));
								listItem.setChon_id(jsonObject
										.getString("chon_id"));
								listItem.setTitle(jsonObject.getString("title"));
								listItem.setContent(jsonObject
										.getString("content"));
								listItem.setWr_dt(jsonObject.getString("wr_dt"));
								listItem.setPic_names(jsonObject
										.getString("pic_names"));
								listItem.setSubcontent(jsonObject
										.getString("subcontent"));

								list.add(listItem);

								listItem2 = listItem;
							}
							// mode 0:내용, 1:이미지, 2:댓글

							// 이미지 리스트 추가
							if (listItem2.getPic_names().trim().length() > 0) {
								String[] imageArray = listItem2.getPic_names()
										.trim().split(";");
								
								Log.d(LOGTAG, "imageArray : " + imageArray.length);

								for (int i = 0; i < imageArray.length; i++) {
									DetailContentItem listItem = new DetailContentItem();

									listItem.setMode(1);
									listItem.setIdx(listItem2.getIdx());
									listItem.setPhone_number(listItem2.getPhone_number());
									listItem.setUser_name(listItem2.getUser_name());
									listItem.setChon_id(listItem2.getChon_id());
									listItem.setTitle(listItem2.getTitle());
									listItem.setContent(listItem2.getContent());
									listItem.setWr_dt(listItem2.getWr_dt());
									listItem.setPic_names(imageArray[i].toString().trim());
									listItem.setSubcontent("");

									list.add(listItem);
									
									System.out.println(imageArray[i].toString().trim());
								}
							}

							// 댓글 리스트 추가
							if (listItem2.getSubcontent().trim().length() > 0) {
								
								/*
								 * 여기에서 댓글과 댓글 카운트 추가
								 */
								String[] subContentArray = listItem2.getSubcontent()
										.trim().split("\\|");
								Log.d(LOGTAG, " 리스트 추가 : " + listItem2.getSubcontent().trim());
								
								Log.d(LOGTAG, "subContentArray : " + subContentArray.length);

								for (int i = 0; i < subContentArray.length; i++) {
									Log.d(LOGTAG, "subContentArray[i] : " + subContentArray[i]);
									String[] subArray = subContentArray[i].split("\\`");
									
									Log.d(LOGTAG, "subArray(" + i + ") : " + subArray.length);
									
									DetailContentItem listItem = new DetailContentItem();

									listItem.setMode(2);
									listItem.setIdx(listItem2.getIdx());
									listItem.setPhone_number(listItem2.getPhone_number());
									listItem.setUser_name(subArray[0]);
									listItem.setChon_id(listItem2.getChon_id());
									listItem.setTitle(listItem2.getTitle());
									listItem.setContent(listItem2.getContent());
									listItem.setWr_dt(listItem2.getWr_dt());
									listItem.setPic_names("");
									listItem.setSubcontent(subArray[1]);
									

									list.add(listItem);
									
									Log.d(LOGTAG, subArray[0] + "-" + subArray[1]);
								}
							}

							mHandler.sendEmptyMessage(100);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		progressbar = ProgressDialog.show(this, null, "    Loading........");
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			progressbar.cancel();

			initSubContent();

			if (msg.what == 100) {// 상세 보기
				if (list.size() == 0) {
					Toast.makeText(SA1200.this,
							"DETAIL NO DATA", Toast.LENGTH_LONG)
							.show();
					
					//이전 Intent로 이동
					Intent intent = new Intent();
					setResult(RESULT_OK, intent);
					finish();
					
					//리스트 뷰로 이동
				} else {
					listAdapter = new DetailContentListAdapter(SA1200.this, list);
					listview = (ListView) findViewById(R.id.list);
					listview.setAdapter(listAdapter);
					listview.setDivider(new ColorDrawable(Color.parseColor("#50C785")));
					listview.setDividerHeight(1);
				}
			} else if (msg.what == 200) {// 덧글쓰기
				// 덧글을 쓰레드 write 후 다시 읽어온다.
				readServer();
			} else if (msg.what == 0) {// 데이터 없음
				Toast.makeText(SA1200.this, "NO DATA.",
						Toast.LENGTH_LONG).show();
				
				//이전 Intent로 이동
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				finish();
			} else if (msg.what == -100) {// 에러
				Toast.makeText(SA1200.this,
						"ERROR",
						Toast.LENGTH_LONG).show();
				
				//이전 Intent로 이동
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				finish();
			} else if (msg.what == -200) {// 에러
				Toast.makeText(SA1200.this,
						"삭제할 수 없습니다.",
						Toast.LENGTH_LONG).show();
				
				//이전 Intent로 이동
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				finish();
			}
		}
	};

	private void initSubContent() {
		isSubInit = true;
		((EditText) findViewById(R.id.subContent)).setText("댓글달기");

		// 키보드 숨기기
		imm.hideSoftInputFromWindow(selection.getWindowToken(), 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case 100:
			if (resultCode == RESULT_OK) {
				readServer();
			}
			break;
		case 200:
			if (resultCode == RESULT_OK) {
				readServer();
			}
			break;
		}
	}

}
